from django.contrib import admin
from django.utils import timezone
from django.utils.translation import gettext_lazy as _

from undergraduate.EducationAffairs.models import CompetitionCredit
from undergraduate.InnovationProfessionalSkill.inv_score_dict import INNOVATION_SKILL_SCORE_WINNER
from undergraduate.InnovationProfessionalSkill.models import CompetitionScore
from StudentAffairs.models import Student
from .models import CompetitionRecord, Competition, GuideTeacher, \
    CompetitionGroupMember
from django.utils.safestring import mark_safe
from Common.ImportExportVersionModelAdmin import ImportExportVersionModelAdmin, VersionModelAdmin
from .resource import CompetitionResource, CompetitionRecordResource, CompetitionGroupMemberResource, \
    GuideTeacherResource
from .upmc_inv_dict import COMPETITION_CREDITS_DICT, DICT_PAPER_CREDIT, DICT_PAPER_SCORE

from .models import Paper, PaperMember, Journal, JournalIndex
from .resource import PaperResource, GuideTeacherResource, CompetitionGroupMemberResource
from undergraduate.EducationAffairs.models import PaperCredit
from undergraduate.InnovationProfessionalSkill.models import PaperScore


class CompetitionRecordGroupMemberInline(admin.TabularInline):
    model = CompetitionGroupMember
    pass


class CompetitionRecordGuideTeacherInline(admin.TabularInline):
    model = GuideTeacher
    pass


class CompetitionAdmin(ImportExportVersionModelAdmin):
    list_display = ["id", "I_CP_name", "I_CP_effective"]
    list_editable = ["I_CP_effective"]
    resource_class = CompetitionResource
    pass


admin.site.register(Competition, CompetitionAdmin)


class CompetitionRecordAdmin(ImportExportVersionModelAdmin):
    resource_class = CompetitionRecordResource
    inlines = [CompetitionRecordGroupMemberInline, CompetitionRecordGuideTeacherInline]
    list_display = ["id", "I_CR_competition", "I_CR_works_name", "I_CR_confirm", "I_CR_adder", "I_CR_added_time"]
    list_filter = ["I_CR_confirm", "I_CR_added_time"]
    search_fields = ["I_CR_competition_name", "I_CR_adder__username"]
    readonly_fields = ["I_CR_adder", "I_CR_added_time", "I_CR_confirmer", "I_CR_confirmed_time", "I_CR_last_updater",
                       "I_CR_last_updated_time", "proof_preview", "I_CR_competition_name"]

    def proof_preview(self, obj):
        return mark_safe(
            '<img src="%s" class="img-responsive center-block" style="width:100%%" />' % obj.I_CR_proof.url)

    proof_preview.short_description = _("Proof Preview")

    def save_model(self, request, obj: CompetitionRecord, form, change):

        UPMC_SPECIAL_COMPETITION = [
            "“挑战杯”中国大学生创业计划竞赛（“创青春”全国大学生创业大赛）",
            "“挑战杯”全国大学生课外学术科技作品竞赛",
            "中国“互联网+”大学生创新创业大赛",
        ]

        obj.I_CR_competition_name = obj.I_CR_competition.I_CP_name

        if not obj.I_CR_adder:
            obj.I_CR_adder = request.user
        if obj.I_CR_confirm == "通过":
            obj.I_CR_confirmer = request.user
            obj.I_CR_confirmed_time = timezone.localtime(
                timezone=timezone.get_default_timezone())  # .strftime("%Y-%m-%d %H:%M:%S")
            # Delete the old record
            competition_credit = CompetitionCredit.objects.select_related().filter(
                E_CC_competition_record=obj,
            ).delete(
            )
            competiton_score = CompetitionScore.objects.select_related().filter(
                C_CS_competition_record=obj,
            ).delete(
            )
            # Add Credit to 3 dept.
            student_list = obj.competition_record_related_group_member.all()
            for gm_student in student_list:
                sm_student = Student.objects.filter(S_SD_id=gm_student.I_GM_id)
                if len(sm_student) > 0:
                    # SM Student
                    # UPMC
                    # Credits calc
                    credit = COMPETITION_CREDITS_DICT[gm_student.I_GM_leader][obj.I_CR_level][obj.I_CR_prize]
                    if obj.I_CR_competition.I_CP_name in UPMC_SPECIAL_COMPETITION:
                        credit += 1

                    # add new one
                    competition_credit = CompetitionCredit(
                        E_CC_student=sm_student.first(),
                        E_CC_competition_record=obj,
                        E_CC_competition_name=obj.I_CR_competition.I_CP_name,
                        E_CC_student_id=sm_student.first().S_SD_id,
                        E_CC_student_name=sm_student.first().S_SD_name,
                        E_CC_credits=credit,
                    )
                    competition_credit.save()
                    # SAO
                    score = INNOVATION_SKILL_SCORE_WINNER[gm_student.I_GM_leader][obj.I_CR_level][obj.I_CR_prize]
                    # add new one
                    competition_score = CompetitionScore(
                        C_CS_student=sm_student.first(),
                        C_CS_date=obj.I_CR_award_date,
                        C_CS_semester=obj.I_CR_semester,
                        C_CS_score=score,
                        C_CS_prize_name=obj.I_CR_prize_name,
                        C_CS_competition_name=obj.I_CR_competition.I_CP_name,
                        C_CS_competition_record=obj,
                        C_CS_competition_experience_record=None,
                    )
                    competition_score.save()
                    # INP
                    pass
                else:
                    # No such student
                    continue
        else:
            # Not passed
            obj.I_CR_confirmer = request.user
            obj.I_CR_confirmed_time = timezone.localtime(
                timezone=timezone.get_default_timezone())  # .strftime("%Y-%m-%d %H:%M:%S")

            # Delete the old record
            competition_credit = CompetitionCredit.objects.select_related().filter(
                E_CC_competition_record=obj,
            ).delete(
            )  # Keep_parents is optional because we don't use a succeed object
            CompetitionScore.objects.select_related().filter(
                C_CS_competition_record=obj,
            ).delete()

        if not obj.I_CR_last_updater:
            obj.I_CR_last_updater = request.user
        super().save_model(request, obj, form, change)

    pass


admin.site.register(CompetitionRecord, CompetitionRecordAdmin)


class CompetitionGroupMemberAdmin(ImportExportVersionModelAdmin):
    resource_class = CompetitionGroupMemberResource
    list_display = [
        'I_GM_id',
        'I_GM_name',
        'I_GM_record',
        'I_GM_tel',
        'I_GM_leader',
    ]
    list_filter = ["I_GM_record", ]


admin.site.register(CompetitionGroupMember, CompetitionGroupMemberAdmin)


class GuideTeacherAdmin(ImportExportVersionModelAdmin):
    resource_class = GuideTeacherResource
    list_display = ["I_GT_record", "I_GT_id", "I_GT_name", "I_GT_school",
                    ]
    list_filter = ["I_GT_record", ]


admin.site.register(GuideTeacher, GuideTeacherAdmin)


# Register your models here.

# class PaperMemberInline(admin.TabularInline):
#     model = PaperMember
#     pass
#
#
class JournalAdmin(admin.ModelAdmin):
    pass


admin.site.register(Journal, JournalAdmin)


#
#
class JournalIndexAdmin(admin.ModelAdmin):
    list_display = ["pk", "index_name", "index_type"]
    list_editable = ["index_type"]


admin.site.register(JournalIndex, JournalIndexAdmin)


class PaperAdmin(ImportExportVersionModelAdmin):
    resource_class = PaperResource
    list_display = ["paper_name", "journal", "author_count", "confirm_status"]
    list_filter = ["confirm_status"]
    search_fields = ["paper_name"]
    readonly_fields = ['add_by', 'add_time', 'confirm_by', 'confirm_time', 'proof_preview']

    def proof_preview(self, obj):
        return mark_safe(
            '<img src="%s" class="img-responsive center-block" style="width:100%%" />' % obj.proof.url)

    proof_preview.short_description = _("Proof Preview")

    def save_model(self, request, obj: Paper, form, change):
        obj.confirm_by = request.user
        obj.confirm_time = timezone.localtime(timezone=timezone.get_default_timezone())
        super().save_model(request, obj, form, change)


admin.site.register(Paper, PaperAdmin)


@admin.register(PaperMember)
class PaperMemberAdmin(VersionModelAdmin):
    list_display = ['paper', 'student', 'paper_confirm_status', 'order', 'confirm_status']
    list_editable = ['confirm_status']

    def paper_confirm_status(self, obj: PaperMember):
        return '%s' % (obj.paper.confirm_status,)

    paper_confirm_status.short_description = _('Paper Confirm Status')

    def save_model(self, request, obj: PaperMember, form, change):
        obj.confirm_by = request.user
        obj.confirm_time = timezone.localtime(timezone=timezone.get_default_timezone())
        if obj.confirm_status == "通过":
            PaperCredit.objects.select_related().filter(E_PC_paper_record=obj.paper, E_PC_student=obj.student).delete()
            PaperScore.objects.select_related().filter(C_PS_paper=obj.paper, C_PS_student=obj.student).delete()

            paper_credit = paper_credit = PaperCredit(
                E_PC_student=obj.student,
                E_PC_paper_record=obj,
                E_PC_paper_name=obj.paper.paper_name,
                E_PC_student_name=obj.student.S_SD_name,
            )
            paper_score = PaperScore(
                C_PS_student=obj.student,
                C_PS_semester=obj.paper.publish_semester,
                C_PS_paper=obj.paper,
                C_PS_paper_name=obj.paper.paper_name,
                C_PS_author_order=obj.order,
                C_PS_is_teacher_leader=obj.paper.is_teacher_first_author,
                C_PS_journal_type=obj.paper.journal.journal_index.index_type,
            )
            credit = 0
            score = 0

            journal_type = obj.paper.journal.journal_index.index_type
            if journal_type == 15:
                super().save_model(request, obj, form, change)
                return
            member_order = obj.order
            member_num = obj.paper.author_count

            if obj.paper.is_teacher_first_author:
                member_order -= 1
                member_num -= 1
                if member_order < 1:
                    member_order = 1
                if member_num < 1:
                    member_num = 1
                    # TODO: warning

            if member_order <= 4:
                credit = DICT_PAPER_CREDIT[journal_type][member_order]

            if member_order == 1:
                score = DICT_PAPER_SCORE[journal_type]
            elif member_order == 2:
                score = DICT_PAPER_SCORE[journal_type] / 2
            else:
                score = DICT_PAPER_SCORE[journal_type] / 2 / (member_num - 2)

            paper_credit.E_PC_credits = credit
            paper_score.C_PS_score = score
            paper_credit.save()
            paper_score.save()
        else:
            PaperCredit.objects.select_related().filter(E_PC_paper_record=obj.paper, E_PC_student=obj.student).delete()
            PaperScore.objects.select_related().filter(C_PS_paper=obj.paper, C_PS_student=obj.student).delete()

        super().save_model(request, obj, form, change)

# def save_model(self, request, obj: Paper, form, change):
#     # if request.user.is_superuser or not obj.add_by:
#     #     obj.add_by = request.user
#
#     if obj.confirm_status == "通过":
#         obj.confirm_by = request.user
#         obj.confirm_time = timezone.localtime(timezone=timezone.get_default_timezone())
#
#         PaperCredit.objects.select_related().filter(E_PC_paper_record=obj).delete()
#         PaperScore.objects.select_related().filter(C_PS_paper=obj).delete()
#
#         member_list = obj.paper_related_member.all()
#         for m in member_list:
#             student = Student.objects.filter(S_SD_id=m.I_PM_id).first()
#             paper_credit = PaperCredit(
#                 E_PC_student=student,
#                 E_PC_paper_record=obj,
#                 E_PC_paper_name=obj.paper_name,
#                 E_PC_student_name=m.I_PM_name,
#             )
#
#             paper_score = PaperScore(
#                 C_PS_student=student,
#                 C_PS_semester=m.I_PM_paper.I_PP_semester,
#                 C_PS_paper=obj,
#                 C_PS_paper_name=m.I_PM_paper.I_PP_name,
#                 C_PS_author_order=m.I_PM_order,
#                 C_PS_is_teacher_leader=m.I_PM_is_teacher_first_author,
#                 C_PS_journal_type=m.I_PM_paper.I_PP_journal.I_JN_index.JOURNAL_TYPES,
#             )
#
#             credit = 0
#             score = 0
#
#             journal_type = m.I_PM_paper.I_PP_journal.I_JN_index.I_JI_journal_type
#             member_order = m.I_PM_order
#             member_num = m.I_PM_paper.I_PP_author_num
#
#             if m.I_PM_is_teacher_first_author:
#                 member_order -= 1
#                 member_num -= 1
#                 if member_order < 1:
#                     member_order = 1
#                 if member_num < 1:
#                     member_num = 1
#                     # TODO: warning
#
#             if member_order <= 4:
#                 credit = DICT_PAPER_CREDIT[journal_type][member_order]
#
#             if member_order == 1:
#                 score = DICT_PAPER_SCORE[journal_type]
#             elif member_order == 2:
#                 score = DICT_PAPER_SCORE[journal_type] / 2
#             else:
#                 score = DICT_PAPER_SCORE[journal_type] / 2 / (member_num - 2)
#
#             paper_credit.E_PC_credits = credit
#             paper_score.C_PS_score = score
#             paper_credit.save()
#             paper_score.save()
#     else:
#         obj.I_PP_confirm_by = request.user
#         obj.I_PP_confirm_time = timezone.localtime(timezone=timezone.get_default_timezone())
#
#         PaperCredit.objects.select_related().filter(
#             E_PC_paper_record=obj
#         ).delete()
#         PaperScore.objects.select_related().filter(
#             C_PS_paper=obj
#         ).delete()
#
#     super().save_model(request, obj, form, change)

#
#
# class PaperAdmin(ImportExportVersionModelAdmin):
#     resource_class = PaperResource
#     inlines = [PaperMemberInline]
#     list_display = ["I_PP_name", "I_PP_journal", "I_PP_index", "I_PP_author_num", "I_PP_confirm_status"]
#     list_filter = ['I_PP_confirm_status']
#     search_fields = ['i_PP_journal_name']
#     readonly_fields = ['I_PP_add_by', 'I_PP_add_time', 'I_PP_confirm_by', 'I_PP_confirm_time', 'proof_preview',
#                        'I_PP_journal_name', 'I_PP_index']
#
#     def proof_preview(self, obj):
#         return mark_safe(
#             '<img src="%s" class="img-responsive center-block" style="width:100%%" />' % obj.I_PP_proof.url)
#
#     proof_preview.short_description = _("Proof Preview")
#
#     def save_model(self, request, obj: Paper, form, change):
#         obj.I_PP_journal_name = obj.I_PP_journal.I_JN_name
#
#         if request.user.is_superuser or not obj.I_PP_add_by:
#             obj.I_PP_add_by = request.user
#
#         if obj.I_PP_confirm_status == "通过":
#             obj.I_PP_confirm_by = request.user
#             obj.I_PP_confirm_time = timezone.localtime(timezone=timezone.get_default_timezone())
#
#             PaperCredit.objects.select_related().filter(E_PC_paper_record=obj).delete()
#             PaperScore.objects.select_related().filter(C_PS_paper=obj).delete()
#
#             member_list = obj.paper_related_member.all()
#             for m in member_list:
#                 student = Student.objects.filter(S_SD_id=m.I_PM_id).first()
#                 paper_credit = PaperCredit(
#                     E_PC_student=student,
#                     E_PC_paper_record=obj,
#                     E_PC_paper_name=obj.I_PP_name,
#                     E_PC_student_name=m.I_PM_name,
#                 )
#
#                 paper_score = PaperScore(
#                     C_PS_student=student,
#                     C_PS_semester=m.I_PM_paper.I_PP_semester,
#                     C_PS_paper=obj,
#                     C_PS_paper_name=m.I_PM_paper.I_PP_name,
#                     C_PS_author_order=m.I_PM_order,
#                     C_PS_is_teacher_leader=m.I_PM_is_teacher_first_author,
#                     C_PS_journal_type=m.I_PM_paper.I_PP_journal.I_JN_index.JOURNAL_TYPES,
#                 )
#
#                 credit = 0
#                 score = 0
#
#                 journal_type = m.I_PM_paper.I_PP_journal.I_JN_index.I_JI_journal_type
#                 member_order = m.I_PM_order
#                 member_num = m.I_PM_paper.I_PP_author_num
#
#                 if m.I_PM_is_teacher_first_author:
#                     member_order -= 1
#                     member_num -= 1
#                     if member_order < 1:
#                         member_order = 1
#                     if member_num < 1:
#                         member_num = 1
#                         # TODO: warning
#
#                 if member_order <= 4:
#                     credit = DICT_PAPER_CREDIT[journal_type][member_order]
#
#                 if member_order == 1:
#                     score = DICT_PAPER_SCORE[journal_type]
#                 elif member_order == 2:
#                     score = DICT_PAPER_SCORE[journal_type] / 2
#                 else:
#                     score = DICT_PAPER_SCORE[journal_type] / 2 / (member_num - 2)
#
#                 paper_credit.E_PC_credits = credit
#                 paper_score.C_PS_score = score
#                 paper_credit.save()
#                 paper_score.save()
#         else:
#             obj.I_PP_confirm_by = request.user
#             obj.I_PP_confirm_time = timezone.localtime(timezone=timezone.get_default_timezone())
#
#             PaperCredit.objects.select_related().filter(
#                 E_PC_paper_record=obj
#             ).delete()
#             PaperScore.objects.select_related().filter(
#                 C_PS_paper=obj
#             ).delete()
#
#         super().save_model(request, obj, form, change)
#
#
# admin.site.register(Paper, PaperAdmin)
